import datetime
import json
import sqlite3

import requests


def createTable(databaseConnection):
    sql_create = """
                create table signReport(
                        time varchar(20),
                        content varchar(100)
                )
    """
    cur = databaseConnection.cursor()
    cur.execute(sql_create)
    cur.close()


def reportDate(databaseConnection, date):
    insertSql = "insert into signReport (time, content) VALUES ( ?, ?)"
    cur = databaseConnection.cursor()
    time = (datetime.datetime.now() + datetime.timedelta(minutes=5)).strftime("%Y-%m-%d %H:%M:%S")
    cur.execute(insertSql, (time, str(date)))
    databaseConnection.commit()
    cur.close()


def selectDate(databaseConnection):
    selectSql = '''select * from signReport'''
    cur = databaseConnection.cursor()
    res = cur.execute(selectSql)
    data = res.fetchall()
    cur.close()
    return data


def detectTime(beforeTime):
    upperTime = (datetime.datetime.now() + datetime.timedelta(minutes=5)).strftime("%H:%M:%S")
    if beforeTime != upperTime.split(':')[0]:
        return True, upperTime.split(':')[0]
    else:
        return False, beforeTime


def postServer(header,body):
    host = 'http://reportedh5.17wanxiao.com'
    router = '/sass/api/epmpics'
    url = host + router
    res = requests.post(url, headers=header, data=json.dumps(body))
    return res


def deleteDate(databaseConnection):
    deleteSql = "delete from signReport"
    cur = databaseConnection.cursor()
    cur.execute(deleteSql)
    databaseConnection.commit()
    cur.close()
def readJson(filePath):
    with open(filePath, 'r', encoding='utf8') as fp:
        json_data = json.load(fp)
    return json_data
def readHear(filePath):
    header = {}
    with open(filePath, 'r', encoding='utf8') as hd:
        headers = hd.readlines()
        for i in headers:
            if len(i) >= 4:
                key = i.split(" ")[0].strip(":")
                value = ""
                for j in range(len(i.split(" "))):
                    if j != 0:
                        value += i.split(" ")[j].replace("\n", "").replace(" ","").strip("\n")
                header.update({key: value.strip("\n")})
    return header
if __name__ == '__main__':
    # con = sqlite3.connect('programReport.db')
    # deleteDate(con)
    # con.commit()
    beforeTime = 0
    con = sqlite3.connect('programReport.db')
    header = readHear("header.txt")
    body = readJson("body.json")
    while True:
        res, beforeTime = detectTime(beforeTime)
        if res:
            res = postServer(header,body)
            reportDate(con, res.json())
            resReport = selectDate(con)
            print('*' * 120)
            for i in resReport:
                print(i)
            print('*' * 120)
            con.commit()
        else:
            pass

